package com.tc.itfarm.service.impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import com.tc.itfarm.api.model.SingleTableDao;
import com.tc.itfarm.api.util.DateUtils;
import com.tc.itfarm.dao.PrivilegeDao;
import com.tc.itfarm.model.Privilege;
import com.tc.itfarm.model.UserRole;
import com.tc.itfarm.service.UserRoleService;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.tc.itfarm.dao.RolePrivilegeDao;
import com.tc.itfarm.model.RolePrivilege;
import com.tc.itfarm.model.RolePrivilegeCriteria;
import com.tc.itfarm.service.RolePrivilegeService;
import org.springframework.util.Assert;

@Service
public class RolePrivilegeServiceImpl extends BaseServiceImpl<RolePrivilege> implements RolePrivilegeService {

	@Resource
	private RolePrivilegeDao rolePrivilegeDao;
	@Resource
	private UserRoleService userRoleService;
	@Resource
	private PrivilegeDao privilegeDao;
	
	@Override
	public List<RolePrivilege> selectByRoleId(List<Integer> roleIds) {
		if (roleIds.size() == 0) {
			return Lists.newArrayList();
		}
		RolePrivilegeCriteria criteria = new RolePrivilegeCriteria();
		criteria.or().andRoleIdIn(roleIds);
		return rolePrivilegeDao.selectByCriteria(criteria);
	}

	@Override
	public List<RolePrivilege> selectByRoleId(Integer roleId) {
		Assert.notNull(roleId);
		RolePrivilegeCriteria criteria = new RolePrivilegeCriteria();
		criteria.or().andRoleIdEqualTo(roleId);
		return rolePrivilegeDao.selectByCriteria(criteria);
	}

	@Override
	public List<RolePrivilege> selectByUserId(Integer userId) {
		List<UserRole> userRoles = userRoleService.selectByUserId(userId);
		List<Integer> roleIds = Lists.newArrayList();
		for (UserRole ur : userRoles) {
			roleIds.add(ur.getRoleId());
		}
		return this.selectByRoleId(roleIds);
	}

	@Override
	public boolean insertAll(Integer id, List<Integer> privilegeIds) throws SQLException{
		// 查询原有的权限
		List<RolePrivilege> rolePrivileges = this.selectByRoleId(id);
		List<Integer> delIds = Lists.newArrayList();
		// 要插入的权限
		for (RolePrivilege rp : rolePrivileges) {
			if (!privilegeIds.contains(rp.getPrivilegeId())) {
				delIds.add(rp.getRecordId());
			} else {
				privilegeIds.remove(rp.getPrivilegeId());
			}
		}
		for (Integer recordId : delIds) {
			this.delete(recordId);
		}
		for (Integer priId : privilegeIds) {
			RolePrivilege rp = new RolePrivilege();
			rp.setRoleId(id);
			rp.setPrivilegeId(priId);
			rp.setCreateTime(DateUtils.now());
			rp.setPrivilegeCode(privilegeDao.selectById(priId).getPrivilegeCode());
			this.insert(rp);
		}
		return true;
	}

	@Override
	protected SingleTableDao getSingleDao() {
		return rolePrivilegeDao;
	}
}
